package com.boot.base.common.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public abstract class DownUtils {

    /**
     * @param source
     * @param filePath
     */
    public static void img(String source, String filePath) {
        URL url = null;
        try {
            url = new URL(source);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // conn.setRequestMethod("GET");
        conn.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        conn.setConnectTimeout(5 * 1000);
        InputStream inStream = null;// 通过输入流获取图片数据
        try {
            inStream = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (true) {
            try {
                if (!((len = inStream.read(buffer)) != -1)) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            outStream.write(buffer, 0, len);
        }
        byte[] btImg = outStream.toByteArray();// 得到图片的二进制数据
        try {
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        conn.disconnect();
        try {
            File file = new File(filePath);
            DirectoryUtil.createFilePath(filePath);
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(btImg);
            fops.flush();
            fops.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void download(String urlString, String filePath) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File file = new File(filePath);
        DirectoryUtil.createFilePath(filePath);
        FileOutputStream os = new FileOutputStream(file, true);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }
}
